<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <!-- 搜索条件 -->
        <el-form ref="queryRef" :inline="true" v-model="queryParams" label-width="68px">
          <el-form-item label="策略实例" prop="strategyInstance">
            <el-input
              v-model="queryParams.strategyInstance"
              placeholder="请输入策略实例"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="参数名称" prop="paramName">
            <el-input
              v-model="queryParams.paramName"
              placeholder="请输入参数名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 工具按钮 -->
    <el-row :gutter="20" style="margin-bottom: 10px;">
      <el-col :span="8">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['kylin:futureStrategyParam:add']"
        >
          新增
        </el-button>
        <el-button
          type="danger"
          icon="Delete"
          @click="handleDelete"
          :disabled="multiple"
          v-hasPermi="['kylin:futureStrategyParam:remove']"
        >
          批量删除
        </el-button>
        <el-button
          type="warning"
          icon="Delete"
          @click="handleTruncate"
          v-hasPermi="['kylin:futureStrategyParam:truncate']"
        >
          清空全部参数
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="strategyParamList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false" />
      <el-table-column
        label="策略实例"
        align="center"
        prop="strategyInstance"
        width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="参数名称"
        align="center"
        prop="paramName"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="参数值"
        align="center"
        prop="paramValue"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['kylin:futureStrategyParam:edit']"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['kylin:futureStrategyParam:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改期货策略参数对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="strategyParamRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="策略实例" prop="strategyInstance">
          <el-input
            v-model="form.strategyInstance"
            placeholder="请输入策略实例"
          />
        </el-form-item>
        <el-form-item label="参数名称" prop="paramName">
          <el-input
            v-model="form.paramName"
            placeholder="请输入参数名称"
          />
        </el-form-item>
        <el-form-item label="参数值" prop="paramValue">
          <el-input
            v-model="form.paramValue"
            placeholder="请输入参数值"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FutureStrategyParam">
import {
  listFutureStrategyParam,
  getFutureStrategyParam,
  addFutureStrategyParam,
  updateFutureStrategyParam,
  delFutureStrategyParam,
  truncateFutureStrategyParam
} from '@/api/kylin/futureStrategyParam';
import {ref, reactive, onMounted, toRefs} from 'vue';
import { useRoute } from 'vue-router';

const {proxy} = getCurrentInstance();
const route = useRoute();

const strategyParamList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    strategyInstance: undefined,
    paramName: undefined
  },
  rules: {
    strategyInstance: [
      {required: true, message: '策略实例不能为空', trigger: 'blur'},
      {min: 1, max: 100, message: '策略实例长度不能超过100个字符', trigger: 'blur'}
    ],
    paramName: [
      {required: true, message: '参数名称不能为空', trigger: 'blur'},
      {min: 1, max: 50, message: '参数名称长度不能超过50个字符', trigger: 'blur'}
    ],
    paramValue: [
      {required: true, message: '参数值不能为空', trigger: 'blur'},
      {min: 1, max: 2000, message: '参数值长度不能超过2000个字符', trigger: 'blur'}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 初始化加载，检查路由参数 */
function initData() {
  // 检查URL中是否有instance参数
  const instance = route.query.instance;
  if (instance) {
    // 设置策略实例查询条件
    queryParams.value.strategyInstance = instance;
    return true;
  }
  return false;
}

/** 查询期货策略参数列表 */
function getList() {
  loading.value = true;
  listFutureStrategyParam(queryParams.value).then(response => {
    // 检查response结构并正确赋值
    if (response.rows && response.total) {
      // 如果数据直接在response中
      strategyParamList.value = response.rows;
      total.value = response.total;
    } else if (response.data) {
      // 如果数据在response.data中
      const data = response.data || {rows: [], total: 0};
      strategyParamList.value = data.rows || [];
      total.value = data.total || 0;
    } else {
      // 默认空数据
      strategyParamList.value = [];
      total.value = 0;
    }

    loading.value = false;
  }).catch(error => {
    console.error('查询数据失败:', error);
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm('strategyParamRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加期货策略参数';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const paramId = row.id || ids.value;
  getFutureStrategyParam(paramId).then(response => {
    // 检查响应数据结构并正确赋值
    if (response && response.data) {
      // 如果数据在response.data中
      const data = response.data;
      form.value.id = data.id;
      // 处理字段名转换：下划线转驼峰
      form.value.strategyInstance = data.strategy_instance || data.strategyInstance;
      form.value.paramName = data.param_name || data.paramName;
      form.value.paramValue = data.param_value || data.paramValue;
    }
    open.value = true;
    title.value = '修改期货策略参数';
  }).catch(error => {
    console.error('获取单个期货策略参数数据失败:', error);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['strategyParamRef'].validate(valid => {
    if (valid) {
      if (form.value.id) {
        updateFutureStrategyParam(form.value.id, form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        }).catch(error => {
          console.error('修改失败:', error);
          proxy.$modal.msgError('修改失败，请重试');
        });
      } else {
        addFutureStrategyParam(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        }).catch(error => {
          console.error('新增失败:', error);
          proxy.$modal.msgError('新增失败，请重试');
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const paramIds = row.id ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除期货策略参数？').then(() => {
    return delFutureStrategyParam(paramIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess('删除成功');
  }).catch(() => {
  });
}

/** 清空全部参数按钮操作 */
function handleTruncate() {
  proxy.$modal.confirm('此操作将清空全部策略参数，且无法恢复，确认继续？').then(() => {
    return truncateFutureStrategyParam();
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess('清空成功');
  }).catch(() => {
  });
}

// 组件初始化查询
onMounted(() => {
  const hasInstanceParam = initData();
  // 无论是否有实例参数，都调用getList()来加载数据
  getList();
});
</script>

<style scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  .small-padding .el-button {
    padding: 0;
  }

  .fixed-width {
    width: 150px;
  }
</style>